package com.lmm.cg.zjgcg.pages.rnplugins;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;

import com.blankj.utilcode.util.DeviceUtils;
import com.facebook.react.bridge.Callback;
import com.lmm.cg.zjgcg.config.AppKeyValueUtils;
import com.lmm.cg.zjgcg.pages.RNMainActivity;
import com.lmm.cg.zjgcg.service.DownloadAppService;
import com.lmm.dresswisdom.lmmframe.components.alert.AlertUtils;
import com.lmm.dresswisdom.lmmframe.reactnative.BasePlugin;
import com.lmm.dresswisdom.lmmframe.reactnative.annotation.RNPlugin;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;

import java.util.Map;

@RNPlugin(method = "updateApp")
public class UpdateAppPlugin extends BasePlugin<RNMainActivity> {

    String downLoadUrl = "";

    public UpdateAppPlugin(RNMainActivity act) {
        super(act);
    }

    @Override
    protected void doAction(Map<String, Object> map, Callback callback) {

        if (map.containsKey("url")) {
            LogUtils.write(map.get("url").toString());
            downLoadUrl = map.get("url").toString();
        }

        if (map.containsKey("version")) {
            LogUtils.write(map.get("version").toString());

            AppKeyValueUtils.setValue("version",map.get("version").toString());

            if (!map.get("version").toString().equals(getVerName())) {
                // 提示更新
                AlertUtils.showActionAlert(activity, "软件更新", "检测到新版本" + map.get("version").toString(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(activity, DownloadAppService.class);
                        intent.putExtra("downloadUrl", downLoadUrl);
                        activity.startService(intent);
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
            }
        }


    }


    public String getVerName() {
        String verName = "";
        try {
            verName = activity.getPackageManager().
                    getPackageInfo(activity.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }


}
